package com.huxin.soa.config.controller;

/******************************************
 * @author: 大鹏 (dapeng@51huxin.com)
 * @createDate: 2017/3/24
 * @company: (C) Copyright 阳光互信 2016
 * @since: JDK 1.8
 * @projectName:IntelliJ IDEA
 * @Description:所有客户端查看自己的配置文件信息
 ******************************************/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huxin.soa.config.bean.ViewReq;
import com.huxin.soa.config.util.BaseHttpClient;
import com.huxin.soa.config.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/view")
@Slf4j
public class ViewConfigController {

    private static final String DEFAULT_LABEL = "master";

    @ResponseBody
    @RequestMapping("/")
    public String view(ViewReq viewReq, HttpServletRequest request) {
        String returnVal = null;
        try {
            if(StringUtil.isNull(viewReq.getApplication()) || StringUtil.isNull(viewReq.getProfile())) {
                returnVal = "参数有误！";
            } else {
                String viewGitConfigUrl = gitRepositoryUrlForApp(viewReq, request.getRequestURL().toString());
                returnVal = BaseHttpClient.doGet(viewGitConfigUrl);

                log.info("view url is {}, result is {}", viewGitConfigUrl, returnVal);

                JSONObject gitConfigObject = JSON.parseObject(returnVal);

                gitConfigObject = gitConfigObject.getJSONArray("propertySources").getJSONObject(0);
                returnVal = gitConfigObject.getString("source");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnVal;
    }

    private String gitRepositoryUrlForApp(ViewReq viewReq, String requestURL) {
        StringBuilder viewGitConfigUrl = new StringBuilder();
        viewGitConfigUrl.append(requestURL.substring(0, requestURL.length() - 5));

        viewGitConfigUrl.append(viewReq.getApplication()).append("/")
                .append(viewReq.getProfile()).append("/")
                .append(StringUtil.isNull(viewReq.getLabel()) ? DEFAULT_LABEL : viewReq.getLabel());
        return viewGitConfigUrl.toString();
    }

}
